$(function() {
	validateInit();

	$('#deviceTable').bootstrapTable({
		data : getDatas(),
		striped : true,
		cache : false,
		pagination : true,
		sortable : false,
		toolbar : "#deviceToolbar",
		sidePagination : "client",
		pageNumber : 1,
		pageSize : 10,
		pageList : [ 10, 25, 50, 100 ],
		search : true,
		strictSearch : false,
		showColumns : true,
		clickToSelect : true,
		uniqueId : 'id',
		columns : [ {
			checkbox : true,
		}, {
			field : 'deviceName',
			title : '设备名'
		}, {
			field : 'deviceServiceNumber',
			title : '售后服务号'
		}, {
			field : 'categoryName',
			title : '所属类别'
		}, {
			field : 'operate',
			title : '操作'
		} ],
		onDblClickRow : function(row) {// 双击查看详情
			showDeviceDetail(row);
		}
	});

	$("#deviceTable").bootstrapTable("hideColumn", "id");
});

//父级类别是否选择了
var isBsSuggestSelected = false;
//表单验证
function validateInit() {
	$.validator.addMethod("isBsSuggestSelected", function(value, element) { 
      return isBsSuggestSelected;       
	}, "必须选择给定的设备类别"); 
	
	
	$.validator.addMethod("isOtherNum", function(value, element) { 
		var result = false;
		$.ajax({
			url : "../device/query.action",
			type : "post",
			async: false,
			data : {
				"deviceServiceNumber" : function() {
					var name = $("#updateDeviceForm [name='deviceServiceNumber']").val();
					return name;
				}
			},
			success: function(data) {
				var id = $("#updateDeviceForm [name='id']").val()
				if (data.length == 0) {
					result = true;
				}else if (data.length == 1 && data[0].id == id) {
					result = true;
				}
			},
			error: function() {
				toastr.error("检验售后服务号是否重复发生错误，请联系管理员");
			}
		});
		return result;
	}, "此设备服务号已经存在"); 
	 
	$("#addDeviceForm").validate({
		rules : {
			suggestCategoryId : {
				required : true,
				isBsSuggestSelected : true
			},
			deviceName: {
				required: true
			},
			deviceServiceNumber : {
				required : true,
				remote : {
					url : "../device/query.action",
					type : "post",
					data : {
						"deviceServiceNumber" : function() {
							var name = $("#addDeviceForm [name='deviceServiceNumber']").val();
							return name;
						}
					},
					dataFilter : function(data) {
						if (data == '[]') {//这个判断不可理解，用data.length和$.isEmptyObject()都不好使
							return true;
						}
						return false;
					}
				}
			},
			deviceDesc: {
				required: true,
				minlength: 5,
				maxlength: 500
			}
		},
		messages : {
			deviceServiceNumber : {
				remote : "此设备服务号已经存在"
			}
		},
		success : function(label, element) {// error是lavel标签，element是input标签
			validSuccess(element,label);
		},
		errorPlacement : function(label, element) {
			validError(element,label);
		}
	});
	$("#updateDeviceForm").validate({
		rules : {
			deviceName: {
				required: true
			},
			deviceServiceNumber : {
				required : true,
				isOtherNum: true
			},
			deviceDesc: {
				required: true,
				minlength: 5,
				maxlength: 500
			}
		},
		messages : {
		},
		success : function(label, element) {// error是lavel标签，element是input标签
			validSuccess(element,label);
		},
		errorPlacement : function(label, element) {
			validError(element,label);
		}
	});
}

function getDatas() {
	var devices = '';
	$.ajax({
		url : "../device/query.action",
		type : "post",
		async : false,// 是为了内层ajax在之后访问
		data: {"deviceStatus":"1"},
		success : function(data) {
			$(data).each(function() {
				
				this.categoryName = getCategoryNameById(this.categoryId);
				//操作赋值	
				this.operate='<button class=\'btn btn-primary btn-xs\' onclick=\'updateDevice("'+this.id+'")\'>修改</button>&nbsp;'
						+	'<button class=\'btn btn-info btn-xs\' onclick=\'updateDeviceImg(' + this.id + ')\'>更换图片</button>&nbsp;'
						+	 '<button class=\'btn btn-danger btn-xs\' onclick=\'singleDelete('+ this.id + ')\'>删除</button>';
	
			});
			devices = data;
		},
		error : function() {
			toastr.error("获取设备信息出错，请联系管理员");
		}
	});
	return devices;
}

// 新增设备
function addDevice() {
	formReset("#addDeviceForm");
	addDeviceFormInit();
	$("#addDeviceModal").modal("show");
}

function addDeviceFormInit() {
	$.ajax({
		url: "../category/getAllEquipment.action",
		type: "post",
		success: function(data) {
			var array = [];
			for(var i=0;i<data.length;i++){
			     var temp = {"id":data[i].id, 'word':data[i].categoryName};
			     array.push(temp);
			}
			
			$("#categoryId").bsSuggest("destroy");
			
			var bsSuggestAreaHtml = '<div class="input-group">'
							      +     '<input type="text" placeholder="支持模糊搜索" class="form-control" id="categoryId" name="suggestCategoryId" >'
							      +     '<input type="hidden" name="categoryId" value="-1"/>'
							      +     '<div class="input-group-btn" id="suggestDiv">'
							      +         '<button type="button" class="btn btn-white dropdown-toggle" data-toggle="dropdown">'
							      +             '<span class="caret"></span>'
							      +         '</button>'
							      +         '<ul class="dropdown-menu dropdown-menu-right my-treetable-hover" role="menu">'
							      +         '</ul>'
							      +     '</div>'
							      +  '</div>';
			$("#bsSuggestArea").html(bsSuggestAreaHtml);
			
			$("#categoryId").bsSuggest({
				indexId: 0, 
				indexKey: 1, //data.value 的第几个数据，作为input输入框的显示内容
				data: {'value': array}
			}).on('onSetSelectValue', function (e, keyword) {  
				isBsSuggestSelected = true;
				$("#addDeviceForm [name='categoryId']").val(keyword.id);
				addAttrForm(keyword.id);
			}).on('onUnsetSelectValue', function (e) {  
				isBsSuggestSelected = false;
			});  
		},
		error: function() {
			toastr.error("请求所属类别发生错误，请联系管理员")
		}
	});
}

function addAttrForm(categoryId) {
	$.ajax({
		url: "../attrName/query.action",
		type: "post",
		async: false,//是为了内层ajax在之后访问
		data: {"categoryId":categoryId, "attrNameStatus":"1"},
		success: function(data) {
			var attrFormHtml = '';
			$(data).each(function(){
				attrFormHtml+='<div class="form-group">'
							+	'<label class="col-sm-4 control-label">'+this.attrName+'：</label>'
							+	'<div class="col-sm-6">'
							+		'<input name="param'+this.id+'" class="form-control input-sm" required="required">'
							+	'</div>'
							+ '</div>';
			});
			$("#paramsOfAddDevice").html(attrFormHtml);
		},
		error: function() {
			toastr.error("获取角色信息出错，请联系管理员");
		}
	});
}

// 保存
function addDeviceSave() {
	if (!$("#addDeviceForm").valid()) {
		return false;
	}
	
	var file = $("#addDeviceForm [name='deviceImg']").val();
	if (file == '' || file == null) {
		toastr.error("设备图片不能为空");
		return;
	}
	var datas = new FormData($("#addDeviceForm")[0]);
	$.ajax({
		url : "../device/save.action",
		type : "post",
		data : datas,
		async : false,
		contentType : false,
		processData : false,
		success : function(data) {
			if (data.success == "true") {
				toastr.success("保存成功");
				$("#deviceTable").bootstrapTable("load", getDatas());
			} else {
				toastr.success("后台处理发生错误，请联系管理员");
			}
		},
		error : function() {
			toastr.error("提交请求发生错误，请联系管理员");
		}
	});
	$("#addDeviceModal").modal("hide");
}

function showDeviceDetail(device) {
	var deviceDetailHtml = '<p style="text-align: center; color: #6294AD;"><b>基本信息</b></p>'
		+	'<p>id：' + device.id + '</p>'
		+	'<p>设备名称：' + device.deviceName + '</p>'
		+	'<p>所属类别：' + device.categoryName + '</p>'
		+	'<p>售后服务号：' + device.deviceServiceNumber + '</p>'
		+	'<p>设备描述：<pre style="white-space: pre-wrap !important;word-wrap: break-word !important;">' + device.deviceDesc + '</pre></p>'
		+	'<p>设备图片：<div class="detailImageDiv"><img style="display:block; margin:0 auto;" src="' + device.deviceImageUrl + '"/><div></p>';
	
	$.ajax({
		url:"../deviceAttr/query.action",
		type: "post",
		data: {"deviceId":device.id, "attrStatus":"1"},
		async: false,
		success: function(data) {
			
			deviceDetailHtml+='<hr/><p style="text-align: center; color: #6294AD;"><b>参数信息</b></p>'
			if(data.length == 0) {
				deviceDetailHtml += '无';
			} else {
				$(data).each(function(){
					deviceDetailHtml += '<p>'+getAttrNameName(this.attrNameId)+'：'+this.attrValue+'</p>';
				});
			}
		}
	});
		

	deviceDetailHtml+='<hr/><p style="text-align: center; color: #6294AD;"><b>其他信息</b></p>'
		+	'<p>创建人：' + getUserNameById(device.createUserId) + '</p>'
		+	'<p>创建时间：' + getDefaultTime(device.createTime) + '</p>';
			

	$("#deviceDetailShow").html(deviceDetailHtml);
	$("#deviceDetailModal").modal("show");
}

function updateDeviceParam() {
	window.location.href="../deviceAttr/page.action";
}

//更换图片
function updateDeviceImg(id) {
	$("#updateDeviceImgForm [name='id']").val(id);
	$("#updateDeviceImgModal").modal("show");
}

//修改图片保存
function updateDeviceImgSave() {
	var file = $("#updateDeviceImgForm [name='deviceImg']").val();
	if (file == '' || file == null) {
		toastr.error("设备图片不能为空");
		return;
	}
	
	var fdata = new FormData($("#updateDeviceImgForm")[0]);
	$.ajax({
		url : "../device/updateDeviceImg.action",
		type : "post",
		data : fdata,
	    contentType: false,
	    processData: false ,
		success : function(data) {
			if (data.success == "true") {
				toastr.success("更新成功");
			} else {
				toastr.error("后台处理发生错误，请联系管理员");
			}
		},
		error : function() {
			toastr.error("提交请求发生错误，请联系管理员");
		}
	});
	$("#updateDeviceImgModal").modal("hide");
}

//修改

//修改
function updateDevice(id) {
	formReset("#updateDeviceForm");
	
	$.ajax({
		url : "../device/query.action",
		type : "post",
		async : false,// 是为了内层ajax在之后访问
		data: {"deviceStatus":"1","id":id},
		success : function(data) {
			if (data.length == 1) {
				$("#updateDeviceForm [name='id']").val(id);
				$("#updateDeviceForm [name='deviceName']").val(data[0].deviceName);
				$("#updateDeviceForm [name='deviceServiceNumber']").val(data[0].deviceServiceNumber);
				$("#updateDeviceForm [name='deviceDesc']").text(data[0].deviceDesc);
				
				$("#updateDeviceModal [onclick='updateDeviceSave()']").attr("disabled", "disabled");
				
				$("#updateDeviceForm input,textarea").bind('input', function(){
					$("#updateDeviceModal [onclick='updateDeviceSave()']").removeAttr("disabled");
				});
						
				$("#updateDeviceModal").modal("show");
			} else {
				toastr.error("获取设备信息出错，请联系管理员");
			}
		},
		error : function() {
			toastr.error("获取设备信息出错，请联系管理员");
		}
	});


}
function updateDeviceSave() {
	if (!$("#updateDeviceForm").valid()) {
		return;
	}
	var data = $("#updateDeviceForm").serialize();
	
	$.ajax({
		url : "../device/update.action",
		type : "post",
		data : data,
		success : function(data) {
			if (data.success == "true") {
				toastr.success("更新成功");
				$("#deviceTable").bootstrapTable("load", getDatas());
			}
		},
		error : function() {
			toastr.error("提交请求发生错误，请联系管理员");
		}
	});
	$("#updateDeviceModal").modal("hide");
}
 
// 批量删除
function batchDelete() {
	var selectedRoles = $("#deviceTable").bootstrapTable('getSelections');
	// console.log(JSON.stringify(selectedRoles)); //Array[Object, Object, ...]
	// return;
	if (selectedRoles.length == 0) {
		toastr.error("请勾选你要删除的数据");
		return false;
	}
	var deviceIds = new Array();
	$(selectedRoles).each(function(index, device) {
		deviceIds[index] = device.id;
	})

	deleteCore(deviceIds);

}

// 删除单个客户
function singleDelete(id) {
	var deviceIds = new Array();
	deviceIds[0] = id;
	deleteCore(deviceIds);
}

function deleteCore(deviceIds) {
	swal({
		title : "您确定要删除所选信息吗",
		text : "删除后将无法恢复，请谨慎操作！",
		type : "warning",
		showCancelButton : true,
		confirmButtonColor : "#DD6B55",
		confirmButtonText : "删除",
		closeOnConfirm : false
	}, function() {
		$.ajax({
			url : "../device/deleteDeviceInfo.action",
			type : "post",
			data : {
				"deviceIds" : deviceIds
			},
			success : function(data) {
				if (data.success == "true") {
					swal("删除成功", "您已经永久删除了所选信息。", "success");
					$("#deviceTable").bootstrapTable("load", getDatas());
				} else {
					swal("删除失败", "后台业务处理发生错误，请联系管理员", "error");
				}
			},
			error : function() {
				swal("操作失败", "提交到数据库发生错误，请联系管理员。", "error");
			}
		});
	});
}

